package com.example.activelifecycletest.thread;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.example.activelifecycletest.R;

/**
 * 子线程中更新UI
 * @author zhangding
 * @date 2022年5月10日21:58:32
 */
public class SonThreadActivity extends AppCompatActivity {

    public static final int UPDATE_TEXT = 1;
    private TextView textView;
    private Handler handler = new Handler(){
        public void handleMessage(Message message){
            /*
            发送对象之后的具体处理动作
             */
            switch (message.what){
                case UPDATE_TEXT:
                    textView.setText("你好，这是改变之后的文字！");
                    break;
                default:
                    break;
            }
        }
    };



    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_son_thread);
        Button button = findViewById(R.id.change_text);
        textView =  findViewById(R.id.text);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Message message = new Message();
                        // 确定发送对象后的处理动作
                        message.what = UPDATE_TEXT;
                        // 将Message对象发送出去
                        handler.sendMessage(message);
                    }
                }).start();
            }
        });

    }
}
